import { login, logout, getInfo } from '@/api/login'
import { getToken, setToken, removeUser,removeUserId,removeToken,getUserId,setUserId,setUser } from '@/utils/auth'
import defAva from '@/assets/images/profile.jpg'
import { remove } from 'nprogress';
const route = useRoute();
const router = useRouter();

const useUserStore = defineStore(
  'user',
  {
    state: () => ({
      token: getToken(),
      userid: getUserId() || '',
      name: '',
      avatar: '',
      roles: [],
      permissions: [],
      userInfo: {}
    }),
    actions: {
      // 登录
      login(userInfo) {
        const username = userInfo.username.trim()
        const password = userInfo.password
        const code = userInfo.code
        const uuid = userInfo.uuid
        return new Promise((resolve, reject) => {
          login(username, password, code, uuid).then(res => {

            if(res.success == false){
              setUser(res.data)
              alert(res.msg)
              reject(res.msg)
            }else{
              setToken(res.data.token)
              setUserId(res.data.id)
              this.token = res.data.token
              resolve()
            }

            
          }).catch(error => {
            reject(error)
          })
        })
      },
      // 获取用户信息
      getInfo() {
        return new Promise((resolve, reject) => {

          getInfo(getUserId()).then(res => {
            
            const user = res.data
            const avatar = (user.avatar == "" || user.avatar == null) ? defAva : import.meta.env.VITE_APP_BASE_API + user.avatar;
            
            if (res.data.roleEntities && res.data.roleEntities.length > 0) { // 验证返回的roles是否是一个非空数组
              let roleEntities = res.data.roleEntities;
              this.roles = new Array()
              roleEntities.forEach(element => {
                this.roles.push(element.roleKey)
              });
              this.permissions = new Array()
              let menus = res.data.menus;
              menus.forEach(element => {
                this.permissions.push(element.perms)
              });
            } else {
              this.roles = ['ROLE_DEFAULT']
            }
            this.name = user.username
            this.avatar = avatar;
            this.userInfo = res.data
            resolve(res.data)
          }).catch(error => {
            reject(error)
          })
        })
      },
      // 退出系统
      logOut() {
        return new Promise((resolve, reject) => {
          logout(this.token).then(() => {
            this.token = ''
            this.roles = []
            this.permissions = []
            removeToken()
            removeUser()
            removeUserId()
            resolve()
          }).catch(error => {
            reject(error)
          })
        })
      }
    }
  })

export default useUserStore
